import { useEffect, useState } from 'react';
import { fetchMcpTools } from '../services/api';

export default function McpManager({ open, onClose }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [result, setResult] = useState(null);
  const [expanded, setExpanded] = useState({}); // 服务器是否展开
  const [toolOpen, setToolOpen] = useState({}); // 工具展开收起，结构: { serverName: { toolName: true/false } }

  useEffect(() => {
    if (!open) return;
    const load = async () => {
      setError('');
      setResult(null);
      setLoading(true);
      try {
        const data = await fetchMcpTools();
        setResult({ data });
      } catch (e) {
        console.error(e);
        setError('加载MCP工具列表失败');
      } finally {
        setLoading(false);
      }
    };
    load();
    setToolOpen({}); // 打开时清空工具展开状态
  }, [open]);

  const toggleExpand = (serverName) => {
    setExpanded((prev) => ({ ...prev, [serverName]: !prev[serverName] }));
  };
  // 工具点击展开/收起
  const handleToggleTool = (serverName, toolName) => {
    setToolOpen(prev => ({
      ...prev,
      [serverName]: {
        ...(prev[serverName] || {}),
        [toolName]: !((prev[serverName] || {})[toolName])
      }
    }));
  };

  const renderResult = () => {
    if (!result) return null;
    const { data } = result;
    if (data && data.success === false) {
      return (
        <div className="notice error">
          <div>{data.message || '请求失败'}</div>
          {Array.isArray(data.availableServers) && data.availableServers.length > 0 && (
            <div style={{ marginTop: 8 }}>可用服务器：{data.availableServers.join(', ')}</div>
          )}
        </div>
      );
    }
    // 展示工具回包并确保同名同版本只渲染一次
    const results = Array.isArray(data?.servers) ?
      data.servers.filter((s, idx, arr) =>
        arr.findIndex(ss => ss.serverName === s.serverName && ss.serverVersion === s.serverVersion) === idx)
      : [];
    if (results.length === 0) {
      return <div style={{ color: '#999', padding: 16 }}>暂无服务器</div>;
    }
    return (
      <div className="result-box" style={{marginTop:12}}>
        {results.map((s) => (
          <div key={s.serverName+':'+s.serverVersion} style={{ marginBottom: 16, background: '#fafbfc', borderRadius: 7, boxShadow: '0 1px 3px #f0f1f2' }}>
            <div
              style={{ fontWeight: 700, fontSize: 16, color: '#31383f', display:'flex',alignItems:'center',gap:10, padding:'12px 16px', cursor:'pointer' }}
              onClick={() => toggleExpand(s.serverName)}
            >
              <span style={{ color:'#409eff'}}>{s.serverName}</span>
              {s.serverVersion ? <span style={{ color: '#999', fontWeight: 400, fontSize: 13 }}>v{s.serverVersion}</span> : null}
              <span style={{ color: '#999', fontWeight: 400, fontSize: 13 }}>（工具 {s.toolCount ?? (s.tools?.length || 0)}）</span>
              <span style={{ marginLeft:'auto', color:'#999' }}>{expanded[s.serverName] ? '收起' : '展开'}</span>
            </div>
            {expanded[s.serverName] && (
              <div style={{ padding: '0 16px 12px 16px' }}>
                <ol style={{ listStyle:'decimal', margin: 0, paddingLeft: 24 }}>
                  {(s.tools || []).map((t, idx) => {
                    const toolIsOpen = (toolOpen[s.serverName]||{})[t.name] === true;
                    return (
                      <li
                        key={t.name}
                        style={{
                          padding: '10px 0',
                          borderBottom: idx < (s.tools.length - 1) ? '1px solid #ececec' : 'none',
                          transition: 'background 0.2s',
                          cursor: 'pointer',
                        }}
                        className="mcp-tool-item"
                        onClick={() => handleToggleTool(s.serverName, t.name)}
                      >
                        <div style={{fontWeight: 600, fontSize: 15, color:'#232b39', lineHeight:'22px', userSelect:'none'}}>
                          {t.name}
                          <span style={{ color: '#b1b1b1', marginLeft: 10, fontWeight: 400, fontSize: 12 }}>{toolIsOpen ? '收起详情' : '展开详情'}</span>
                        </div>
                        {t.description && (
                          <div style={{ color: '#888', fontSize: 13, marginLeft: 2, marginTop: 4, marginBottom: 2, lineHeight: '18px' }}>{t.description}</div>
                        )}
                        {toolIsOpen && (
                          <pre style={{
                            background:'#fff',
                            border:'1px solid #eef0f2',
                            borderRadius:6,
                            padding:'8px 10px',
                            fontSize:12,
                            color:'#2c3e50',
                            overflowX:'auto',
                            whiteSpace:'pre-wrap',
                            wordBreak:'break-word',
                            marginTop:4
                          }}>{JSON.stringify(t, null, 2)}</pre>
                        )}
                      </li>
                    );
                  })}
                </ol>
              </div>
            )}
          </div>
        ))}
      </div>
    );
  };

  return (
    <div className={`modal ${open ? 'show' : ''}`} onClick={onClose}>
      <div className="modal-content" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <div className="modal-title">MCP 服务管理</div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <div className="modal-body">
          <div className="form-row" style={{ alignItems: 'center',marginBottom:8 }}>
            <label style={{ marginRight: 8 }}>服务器列表</label>
          </div>
          {error && <div className="notice error" style={{ marginTop: 10 }}>{error}</div>}
          <div style={{ marginTop: 16, minHeight: 48 }}>
            {loading && <div>加载中...</div>}
            {!loading && renderResult()}
          </div>
        </div>
        <div className="modal-footer">
          <div style={{ flex: 1 }} />
          <button className="tool-btn" onClick={onClose}>关闭</button>
        </div>
      </div>
    </div>
  );
}


